package com.example.carbon.controller;


import com.example.carbon.pojo.RestBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/api/upload")
@Slf4j
public class UploadController {


    @PostMapping("/img")
    public RestBean upload(@RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return RestBean.failure(400,"上传的文件为空");
            }
            String originalFileName = file.getOriginalFilename();
            if (originalFileName == null || originalFileName.isEmpty()) {
                return RestBean.failure(400,"文件名无效");
            }
            // 获取文件后缀名
            String fileExtension = originalFileName.substring(originalFileName.lastIndexOf("."));
            // 生成UUID
            String uuid = UUID.randomUUID().toString();
            // 构造文件名
            String newFileName = uuid + fileExtension;
            // 构造完整的文件保存路径
            String directoryPath = "D:\\upload\\file\\img\\";
            String filePath = directoryPath + newFileName;
            File directory = new File(directoryPath);
            if (!directory.exists()) {
                if (!directory.mkdirs()) {
                    return RestBean.failure(500,"文件夹初始化失败");
                }
            }
            file.transferTo(new File(filePath));
            log.info("文件保存成功，路径：" + filePath);
            return RestBean.success(newFileName);
        } catch (IOException e) {
            log.error("文件保存失败：" + e.getMessage());
            return RestBean.failure(500,"文件保存失败");
        }
    }

}
